package com.hsylient.javase.chapter11.demo11;

import lombok.SneakyThrows;

/**
 * 卖票的案列演示线程安全问题
 *
 * 多次运行会出现一张票被两个线程抢到的问题
 *
 * 解决方案 加上synchronized 关键字
 */
public class SellTicket {

    private Integer ticketNumber = 10;
    private Boolean flag = Boolean.TRUE;

    @SneakyThrows
    public synchronized void sell() {
            if (ticketNumber > 0) {
                // 这里要模拟延时 放大问题的发生性
                Thread.sleep(1000);
                System.out.println(Thread.currentThread().getName() + "买到了编号为：" + ticketNumber--);
            } else {
                flag = Boolean.FALSE;
            }
    }

    public static void main(String[] args) {
        SellTicket ticket = new SellTicket();
        new Thread(() -> {
            while (ticket.flag) {
                ticket.sell();
            }
        }).start();

        while (ticket.flag) {
            ticket.sell();
        }
    }
}
